package cn.tedu.boot52.controller;

import cn.tedu.boot52.entity.User;
import cn.tedu.boot52.entity.Weibo;
import cn.tedu.boot52.mapper.WeiboMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        if(user==null){
            return 2;//当前用户未登录
        }


        System.out.println("weibo = " + weibo + ", picFile = " + picFile);
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;

        String dirPath = "E:/upload/weibo";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+fileName;
        picFile.transferTo(new File(filePath));

        weibo.setUrl("/"+fileName);
        weibo.setAuthor(user.getNick());
        weibo.setUserId(user.getId());
        weibo.setCreated(new Date());

        mapper.insert(weibo);
        return 1;//代表发布成功!
    }

    @RequestMapping("/select")
    public List<Weibo> select(){

        return mapper.select();
    }

    @RequestMapping("/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);
    }

    @RequestMapping("/selectMyWeibo")
    public List<Weibo> selectMyWeibo(HttpSession session){
        User user = (User) session.getAttribute("user");
        return mapper.selectByUserId(user.getId());
    }

    @RequestMapping("/delete")
    public void delete(int id){
        Weibo weibo = mapper.selectById(id);
        String filePath = "E:/upload/weibo"+weibo.getUrl();
        new File(filePath).delete();
        mapper.delete(id);
    }

}
